// pages/mine/myStock/myStock.js
const app = getApp(),
    globalData = app.globalData,
    api = require('../../../api/index'),
    http=require('../../../utils/http'),
    utils = require('../../../utils/util');
Page({

    /**
     * 页面的初始数据
     */
    data: {
        sumText:"",
        active: 0,
        status: 0,
        toast: {
            visible: false,
            text: ''
        },
        selfList: [], // 自提列表
        goodsList: [], // 补货列表
        stockList: [], // 库存列表
        filter: {
            keywords: "",
            brandId: "",
            categoryId: "",
            types: [1, 2, 3],
            goodsOnState: 1,
            goodsSortByEnum: 1,
            currenetPageIndex: 1,
            pageSize: 10,
            recordCount: 0
        },
        filter1:{
            currenetPageIndex: 1,
            pageSize: 10,
            recordCount: 10
        },
        filter2: {
            userName: "",
            currenetPageIndex: 1,
            pageSize: 10,
            recordCount: 10
        },
        imageBaseUri: globalData.imageBaseUri,
        chooseArr: [], // 选中的商品列表
        isManage: false, // 管理（删除）
        deleteArr: [], // 删除数组
        banListArr: [], // 库存为0禁止被选择的项目
        chooseAll: false,
        sum: 0
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.setData({
            active: options.tab || 0
        })
        console.log(this.data.active);
        this.reload();

    },

    reload() {
        // this.setData({
        //     active: 0
        // })
        switch (this.data.active) {
            case '0':
                this.getWareHouse();
                break;
            case '1':
                this.getGoodsList();
                break;
            case '2':
                this.getMyGoods();
                break;
            default:
                return;
        }
        // this.getWareHouse()
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {},

    switchtap(e) {
        let tab = e.currentTarget.dataset.tab;
        console.log(tab, 'tab')
        this.setData({
            active: tab,
            chooseArr: [],
            goodsList: this.data.goodsList,
            selfList: this.data.selfList,
            sum: 0
        })
        switch (tab) {
            case '0':
                this.getWareHouse() // 库存
                break;
            case '1':
                this.getGoodsList() // 补货（商品列表）
                break;
            case '2':
                this.getMyGoods() // 自提
                break;
            default:
                return;
        }
    },

    // 获取当前用户自提
    async getMyGoods() {
        wx.showLoading({
            title: '内容加载中',
        })
        let obj = this.data.filter1;
        try {
            let res = await api.balance.myStock(obj),
                data = res.data || {};
            console.log(data, '测试结果')
            let content = data.ResData.Items ? data.ResData.Items : [];
            for (let i = 0; i < content.length; i++) {
                content[i].checked = false;
                content[i].Num = 1;
            }
            if (obj.currenetPageIndex > 1) {
                content = this.data.selfList.concat(content);
            }
            console.log(content,132121322)
            this.setData({
                status: 2,
                selfList: content ? content : []
            })
        } catch (e) {
            console.log(e, '获取自提失败')
            this.setData({
                status: 1
            })
        } finally {
            wx.hideLoading()
        }
    },

    // 获取补货
    ////////////////////////////////
    async getGoodsList() {
        let obj = this.data.filter;
        wx.showLoading({
            title: '内容加载中',
        })
        try {
            let res = await api.goods.getGoodsPages(obj),
                data = res.data.ResData || {};
            console.log(res, '商品列表')
            let content = data.Items ? data.Items : [];
            for (let i = 0; i < content.length; i++) {
                content[i].checked = false;
                content[i].Num = 1;
            }
            if (this.data.filter.currenetPageIndex > 1) {
                data.Items = this.data.goodsList.concat(data.Items);
            }



            data.Items && data.Items.map(item => {
                if (item.MarketingTypes && item.MarketingTypes.toString().indexOf('2') != -1) {
                    item.isSeckill = true;
                } else {
                    item.isSeckill = false;
                }
                if (item.MarketingTypes && item.MarketingTypes.toString().indexOf('3') != -1) {
                    item.isGroup = true;
                } else {
                    item.isGroup = false;
                }
            })

            this.setData({
                cartCount: data.TotalItems || 0,
                goodsList: data.Items || [],
                hasMore:data.TotalItems > data.Items?.length ? true : false,
                status: 2
            })
            console.log(this.data.goodsList, '有没有items')

        } catch (e) {
            console.log(e, '获取补货列表失败')
            this.setData({
                status: 1
            })
        } finally {
            wx.hideLoading()
        }
    },

    // 获取库存
    async getWareHouse() {
        let obj = this.data.filter2;
        obj.userName = wx.getStorageSync('userinfo').NickName;
        wx.showLoading({
            title: '内容加载中',
        })

        try {
            let res = await api.goods.getMyStockGoods(obj),
                data = res.data.ResData || {};
            console.log(res, '库存列表')
            if (this.data.filter2.currenetPageIndex > 1) {
                data.Items = this.data.stockList.concat(data.Items);
            }

            let content = data.Items ? data.Items : [];

            for (let i = 0; i < content.length; i++) {
                content[i].checked = false;
                content[i].Num = 1;
            }

            data.Items && data.Items.map(item => {
                if (item.MarketingTypes && item.MarketingTypes.toString().indexOf('2') != -1) {
                    item.isSeckill = true;
                } else {
                    item.isSeckill = false;
                }
                if (item.MarketingTypes && item.MarketingTypes.toString().indexOf('3') != -1) {
                    item.isGroup = true;
                } else {
                    item.isGroup = false;
                }
            })
            this.setData({
                cartCount: data.TotalItems || 0,
                stockList: data.Items || [],
                hasMore:data.TotalItems > data.Items?.length ? true : false,
                status: 2
            })
        } catch (e) {
            console.log(e, '库存获取失败')
            this.setData({
                status: 1
            })
        } finally {
            wx.hideLoading()
        }
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {
        if (this.data.hasMore) {
            switch (this.data.active) {
                case '0':
                    this.setData({
                        'filter2.currenetPageIndex': ++this.data.filter2.currenetPageIndex
                    });
                    this.getWareHouse()
                    break;
                case '1':
                    this.setData({
                        'filter.currenetPageIndex': ++this.data.filter.currenetPageIndex
                    });
                    this.getGoodsList();
                    break;
                case '2':
                    this.setData({
                        'filter1.currenetPageIndex': ++this.data.filter.currenetPageIndex
                    });
                    this.getMyGoods()
                    break;
                default:
                    return;
            }
        }
    },

    // 单选
    chooseItem(e) {
        console.log(e, 'e', this.data.goodsList, '一选择时的carlist')
        let index = e.currentTarget.dataset.index;
        let carList = this.data.active == 1 ? this.data.goodsList : this.data.active == 2 ? this.data.selfList : [],
            item = carList[index],
            chooseArr = this.data.chooseArr,
            banListArr = this.data.banListArr;
        console.log(item, 'item??')
        // 图标的展示
        item.checked = !item.checked;
        carList[index] = item;
        if (this.data.active == 1) {
            this.setData({
                goodsList: carList
            })
        } else if (this.data.active == 2) {
            this.setData({
                selfList: carList
            })
        }

        if (item.checked) {
            chooseArr.push(item)
        } else {
            chooseArr.splice(chooseArr.indexOf(item), 1)
        }

        this.setData({
            chooseArr
        })

        console.log(this.data.chooseArr, 'chooseArr')

        // 是否所选择项目已经是全部
        if (this.data.chooseArr.length + this.data.banListArr.length == carList.length) {
            this.setData({
                chooseAll: true
            })
        } else {
            this.setData({
                chooseAll: false
            })
        }

        this.getSum();

    },

    // 计算总价
    getSum() {
        let that=this
        let sum = 0,
            chooseArr = this.data.chooseArr;
        chooseArr.forEach(item => {
            sum += (item.Price) * Number(item.Num ? item.Num : 1)
        })
        let {Id}=wx.getStorageSync('userinfo')
        console.log(Id);
        let obj={
            user_id:Id,
            money:sum  
        }
        http.request("post","/Order/PayAmount",obj).then((res)=>{
            console.log(res,"5454545");
            if(res.data.ErrCode==0){
                that.setData({
                    sum:res.data.ResData.money,
                    sumText:res.data.ResData.remake
                })
            }
        })

        // this.setData({
        //     sum
        // })
    },

    // 结算，去订单页面
    submit() {
        console.log("自提");
        // 选中的项目为空，不操作
        if (this.data.chooseArr.length == 0) {
            return
        }
        console.log(this.data.chooseArr, '结算时选择的项目列表')
        let chooseArrStr = encodeURIComponent(JSON.stringify(this.data.chooseArr));

        wx.navigateTo({
            url: `/pages/product/confirm/confirm?goods=${chooseArrStr}&from=${this.data.active == 1 ? 2 : this.data.active == 2 ? 3 : ''}&source='goods'`,
        })

    },

    editNum(e) {
        let idx = e.currentTarget.dataset.index;
        let carList = this.data.active == 1 ? this.data.goodsList : this.data.active == 2 ? this.data.selfList : [],
            item = carList[idx];
        let num = e.detail.value;
        item.Num = num;
        carList[idx] = item;

        if (this.data.active == 1) {
            this.setData({
                goodsList: carList,
            })
        } else if (this.data.active == 2) {
            this.setData({
                selfList: carList
            })
        }

    },

    checkNum(e) {
        let idx = e.currentTarget.dataset.index;
        let carList = this.data.active == 1 ? this.data.goodsList : this.data.active == 2 ? this.data.selfList : [],
            item = carList[idx];

        if (this.data.active == 1 && item.checked) {
            this.getSum()
        }
    },

    // 单项增加
    addOne(e) {
        let idx = e.currentTarget.dataset.index,
            // item = e.currentTarget.dataset.item,
            carList = this.data.active == 1 ? this.data.goodsList : this.data.active == 2 ? this.data.selfList : [],
            item = carList[idx];

        console.log(item, 'item')

        if (item.Num >= item.Stock) {
            this.setData({
                toast: {
                    visible: true,
                    text: '超过库存'
                },
            })
            item.Num = item.Stock;
        } else {
            item.Num = item.Num + 1;
        }

        carList[idx] = item

        if (this.data.active == 1) {
            this.setData({
                goodsList: carList,
            })
        } else if (this.data.active == 2) {
            this.setData({
                selfList: carList
            })
        }

        if (this.data.active == 1 && item.checked) {
            this.getSum()
        }
    },

    // 单项减去
    subOne(e) {
        let idx = e.currentTarget.dataset.index,
            // item = e.currentTarget.dataset.item,
            carList = this.data.active == 1 ? this.data.goodsList : this.data.active == 2 ? this.data.selfList : [],
            item = carList[idx];

        console.log(item, 'item')

        if (item.Num <= 1) {
            this.setData({
                toast: {
                    visible: true,
                    text: '至少购买一个商品'
                },
            })
            item.Num = 1;
        } else {
            item.Num = item.Num - 1;
        }

        carList[idx] = item

        if (this.data.active == 1) {
            this.setData({
                goodsList: carList,
            })
        } else if (this.data.active == 2) {
            this.setData({
                selfList: carList
            })
        }

        if (this.data.active == 1 && item.checked) {
            this.getSum()
        }
    },

    // 跳转
    toDetail(e) {
        wx.navigateTo({
            url: `/pages/product/detail/detail?id=${e.currentTarget.dataset.id}`,
        })
    }
})